import { fileURLToPath, URL } from 'node:url'

import { defineConfig,loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'

// 新增配置
const path = require('path')
import AutoImport from 'unplugin-auto-import/vite'
import {createSvgIconsPlugin} from 'vite-plugin-svg-icons';
import vueSetupExtend from 'vite-plugin-vue-setup-extend'

// https://vitejs.dev/config/
export default defineConfig(({ command, mode }) => {
  const env = loadEnv(mode, process.cwd(), '')
  console.log('当前加载环境变量：', env)
  // define：将全局变量注入到代码中
  // process.env：用于访问运行时的环境变量
  // 使用：import.meta.env.VITE_APP_NAME 或 process.env.VITE_APP_NAME
  return {
    plugins: [
      vue(),
      //自动导入
      AutoImport({
        imports: ["vue", "vue-router", "pinia"],
        dts: "src/types/auto-imports.d.ts",
      }),
      //组件命名
      vueSetupExtend({
        name: true
      }),

      //引入SVG图标素材文件
      createSvgIconsPlugin({
        iconDirs: [path.resolve(process.cwd(), 'src/assets/icons/svg')],
        symbolId: 'icon-[name]'
      })
    ],
    resolve: {
      // https://cn.vitejs.dev/config/#resolve-alias
      alias: {
        // 设置路径
        "~": path.resolve(__dirname, "./"),
        // 设置别名
        "@": path.resolve(__dirname, "./src"),
      },
      // https://cn.vitejs.dev/config/#resolve-extensions
      extensions: [".mjs", ".js", ".ts", ".jsx", ".tsx", ".json", ".vue"],
    },
    server: {
      host: '0.0.0.0',
      proxy: {
        '/api': {
          target: env.VITE_TARGET,  // 将请求代理到目标服务器
          changeOrigin: true,  // 修改请求头中的host字段为目标URL
          rewrite: (path) => path.replace(/^\/api/, ''),  // 重写请求路径，去掉/api前缀
        },
      },
    },
    define: {
      // 'process.env': {
      //   VITE_APP_TITLE: env.VITE_APP_TITLE,
      //   VITE_APP_BASE_URL: env.VITE_APP_BASE_URL
      // }
    }
  }
})
